#!/usr/bin/env node

import inquirer from "inquirer";
import dayjs from "dayjs";
import { isEmpty } from "lodash-es";
import os from "os";
import GitCommitClient from "./core/GitCommitClient.mjs";

const currentTime = dayjs().format("YYYY-MM-DD");

const checkTimeFormat = (time) => {
  const reg = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
  if (reg.test(time)) {
    return true;
  } else {
    return "您输入的时间格式不符，请重新输入";
  }
};

const currentFilePath = () => {
  return os.homedir();
};

const questions1 = [
  {
    type: "input",
    name: "startDate",
    message: "代码提交起始日期，格式：YYYY-MM-DD ,eg：2023-07-03",
    default: currentTime,
    validate: (val) => {
      return checkTimeFormat(val);
    },
  },
  {
    type: "input",
    name: "endDate",
    message: "代码提交截止日期，格式：YYYY-MM-DD ,eg：2023-07-14",
    default: currentTime,
    validate: (val, answers) => {
      const formatValidate = checkTimeFormat(val);
      if (formatValidate === true) {
        const sTime = dayjs(answers.startDate);
        const eTime = dayjs(val);
        if (sTime.isSame(eTime) || sTime.isBefore(eTime)) {
          return true;
        } else {
          return "截止日期不能小于开始日期";
        }
      } else {
        return formatValidate;
      }
    },
  },
  {
    type: "input",
    name: "projectCode",
    message: "请输入ProjectCode",
    validate: (val) => {
      if (isEmpty(val)) {
        return "ProjectCode不能为空";
      }
      return true;
    },
  },
  {
    type: "input",
    name: "repositories",
    message: "请输入本地仓库路径，如果是多个请用半角逗号分割",
    validate: (val) => {
      if (isEmpty(val)) {
        return "仓库路径不能为空";
      }
      return true;
    },
  },
  {
    type: "input",
    name: "exportFilePath",
    message: "请输入导出文件的全路径",
    default: currentFilePath(),
    validate: (val) => {
      if (isEmpty(val)) {
        return "导出文件路径不能为空";
      }
      return true;
    },
  },
];

// 运行函数
const run = async () => {
  const res = await inquirer.prompt(questions1);
  const common = {
    repoId: res.repoId,
    startDate: res.startDate,
    endDate: res.endDate,
    exportFilePath: res.exportFilePath,
    projectCode: res.projectCode,
  };
  const repositories = res.repositories.split(",").map((item) => {
    return {
      path: item,
    };
  });
  // 调用commitClient
  const commitClient = new GitCommitClient(common, repositories);
  commitClient.analyseAllRepo();
  commitClient;
};

run();
